﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Antioch.Base.PlayerStates
{
    internal class SlopeSlide : IState
    {
        public void Enter(StateMachine Machine)
        {
            Machine.DrawComponent.Play("Fall", true);
            Machine.PhysicsComponent.PhysicsBody.GetFixtureList().SetFriction(0.8f);
        }

        public void Leave(StateMachine Machine)
        {

        }

        public void Update(StateMachine Machine)
        {
            if (Machine.Input.Hurt)
            {
                Machine.Transition(typeof(Flinch));
                return;
            }
            
            if (!Machine.PhysicsComponent.IsOnGround)
            {
                Machine.Transition(typeof(Fall));
                return;
            }

            float FloorAngle = Jemgine.Math.Vector.AngleBetweenVectors(
               Jemgine.Math.Vector.Normalize(-Machine.PhysicsComponent.Gravity),
               Machine.PhysicsComponent.GroundNormal);

            if (System.Math.Abs(FloorAngle) < System.Math.PI / 5.0)
            {
                Machine.Transition(typeof(Stand));
                return;
            }
            
            if (FloorAngle < 0) Machine.PlayerEntity.Facing = Jemgine.Data.Facings.Right;
            else Machine.PlayerEntity.Facing = Jemgine.Data.Facings.Left;

            if (Machine.Input.JumpPressed)
            {
                Vector2 Right = Jemgine.Math.Vector.Normalize(Jemgine.Math.Vector.Perpendicular(-Machine.PhysicsComponent.Gravity));

                switch (Machine.PlayerEntity.Facing)
                {
                    case Jemgine.Data.Facings.Left:
                        Machine.PhysicsComponent.PhysicsBody.ApplyLinearImpulse(-Right * Machine.Settings.JumpForce,
                            Machine.PhysicsComponent.PhysicsBody.Position);
                        break;
                    case Jemgine.Data.Facings.Right:
                        Machine.PhysicsComponent.PhysicsBody.ApplyLinearImpulse(Right * Machine.Settings.JumpForce,
                           Machine.PhysicsComponent.PhysicsBody.Position);
                        break;
                }
                Machine.Transition(typeof(Jump));
            }
        }
    }
}
